import http.client
import random


class AgileoneTest:
    def __init__(self):
        self.host = 'localhost'
        self.port = 80
        self.cookie = ''

    def homepage(self):
        conn = http.client.HTTPConnection(self.host, self.port)
        conn.request('GET', '/agileone/')
        setcookie = conn.getresponse().getheader('set-cookie')
        sessionid = setcookie.split(';')[0]
        self.cookie += sessionid + '; '
        print(self.cookie)

    def login(self):
        conn = http.client.HTTPConnection(self.host, self.port)
        param = 'username=admin&password=admin&savelogin=true'
        header = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Cookie': self.cookie}
        conn.request('POST', '/agileone/index.php/common/login', param, header)
        response = conn.getresponse()
        content = response.read().decode()
        if 'successful' in content:
            print('登陆成功.')
        else:
            print('登陆失败.')
        # print(response.getheaders())

        for header in response.getheaders():
            # print(header)
            if header[0] == 'Set-Cookie':
                self.cookie += header[1].split(';')[0] + '; '
        print(self.cookie)

    def add_notice(self):
        sequence = random.randint(10000, 99999)
        conn = http.client.HTTPConnection(self.host, self.port)
        param = 'headline=这是公告管理的标题-%d&content=这是公告管理的内容-%d&scope=a.txt&expireddate=2017-09-12' % (sequence, sequence)
        header = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*', 'Cookie': self.cookie}
        conn.request('POST', '/agileone/index.php/notice/add', param.encode(), header)
        response = conn.getresponse().read()
        nid = response.decode()
        return nid

    def test_add(self):
        nid = self.add_notice()
        # a.txt. 利用数字校验进行响应的简单断言
        if int(nid) > 8:
            print('新增公告-数字校验-成功.')
        else:
            print('新增公告-数字校验-失败.')

            # 2. 利用查询接口进行断言
            # 3. 利用正则表达式对响应进行断言
            # 4. 利用数据库查询对响应时行断言


if __name__ == '__main__':
    at = AgileoneTest()
    at.homepage()
    at.login()
    at.test_add()
